import Taro, { Component } from '@tarojs/taro'
import { Button, Image, Text, View } from '@tarojs/components'
import './index.scss'
import classNames from 'classnames'
import lodash from "@/utils/lodash"
import { formatAmount, headImg, showMemberPrice } from "@/utils/utils"
import { GoodsNumber, MemberPrice, NeedScore, SalePrice, ReceivingAddress } from "@/components/index"
import GoodsPrice from "@/components/goods/goods-price/index"
import { USER_INFO } from "@/config/storage";
import { setReceiveAddress, getReceiveAddress, goodsScore } from '@/utils/storage'


//  处理商品信息
const filterGoodsInfo = i => {
  return {
    skuId: '',
    isSku: i.isSku,
    images: headImg(i.images),
    productId: i.id,
    costPrice: i.costPrice,
    salePrice: i.salePrice,
    memberPrice: i.memberPrice,
    originPrice: i.originPrice,
    stockNumber: i.stockNumber
  }
}

const initGoodsSku = (tagList, skuList) => {
  //  全部属性
  const attrObj = {}
  tagList.map((_item, key) => {
    attrObj[key] = []
  })

  // console.log('skuList', skuList)
  //  从商品中获取全部属性
  skuList.map(sku => {
    sku.skuId = sku.id
    sku.attrList = sku.specSnap.split(',')
    sku.attrList.map((text, key) => {
      attrObj[key].push(text)
    })
  })

  // 商品 sku
  let specList = tagList.map((tag, key) => {
    const { value, ...data } = tag
    const attrs = [...new Set(attrObj[key])]
    const list = value.split(',').filter(text => (attrs.indexOf(text) >= 0))
    return { ...data, list }
  })

  return { specList, skuList }
}

const selectGoodsSku = (checked: Array<string>, specList: Array<any>, skuList: Array<any>) => {
  const check = checked.filter(Boolean)
  //  商品信息
  let goodsInfo = null
  //  商品规格列表
  const tagOrigin = lodash.cloneDeep(specList)

  //  其他规格
  let otherList = []
  tagOrigin.map(tag => {
    tag.options = []
    otherList = otherList.concat(tag.list.filter(i => (check.indexOf(i) == -1)))
  })

  //  sku列表
  skuList.map(sku => {
    const data = [...new Set([...sku.attrList, ...otherList])]
    if (data.length === (otherList.length + check.length)) {
      tagOrigin.map((spec, k) => {
        spec.options.push(sku.attrList[k])
      })

      if (check.length === tagOrigin.length) {
        goodsInfo = sku
      }
    }

    if (data.length === (otherList.length + check.length - 1)) {
      tagOrigin.map((spec, k) => {
        if (spec.list.indexOf(checked[k]) >= 0) {
          spec.options.push(sku.attrList[k])
        }
      })
    }
  })

  //  可选项去重
  tagOrigin.map(tag => {
    tag.options = [...new Set(tag.options)]
  })

  return {
    specList: tagOrigin,
    goodsInfo
  }
}

const fun = function () { }

interface IProps {
  type?: string
}
const prefixCls = 'goods-select'
export default class GoodsSelect extends Component<IProps, {}> {
  state: any
  props: any

  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
    this.state = {
      isShow: false,
      checked: [],
      skuList: [],
      specList: [],
      goodsInfo: {}
    }
  }

  componentWillReceiveProps(nextProps) {
    const { goods } = nextProps
    // console.log('----------------------------------------- init -----------------------------------------')
    //  避免重复渲染
    if (JSON.stringify(this.props.goods) === JSON.stringify(goods)) return

    // console.log('----------------------------------------- init-goods -----------------------------------------')
    //  普通商品渲染
    if (!goods.isSku) {
      this.setState({
        goodsNum: goods.number || 1,
        goodsInfo: filterGoodsInfo(goods),
      })
      return;
    }

    // console.log('----------------------------------------- init-sku -----------------------------------------')
    //  sku 商品渲染
    const { tagSnap, skuDetail } = goods
    let checked = goods.specSnap || []
    const data = initGoodsSku(tagSnap, skuDetail)
    data.specList.map(item => {
      checked.push(lodash.head(item.list))
    })
    const info = selectGoodsSku(checked, data.specList, data.skuList)

    this.setState({
      checked,
      skuList: data.skuList,
      specList: info.specList,
      goodsNum: goods.number || 1,
      goodsInfo: info.goodsInfo || filterGoodsInfo(goods),
    })
  }

  //  确定选择
  onConfirm() {
    const { goods } = this.props
    const { goodsInfo, goodsNum } = this.state
    this.refs.ReceivingAddress.submitData();
    //点击确定储存地址信息
    let receiveAddress = getReceiveAddress();
    if(receiveAddress.addressInfo){
      this.props.onConfirm({ ...goods, ...goodsInfo }, goodsNum)
    }
  }

  /**
   * 设置商品数量
   * @param value 数量
   */
  changeGoodsNum(value) {
    this.setState({
      goodsNum: value
    })
  }

  /**
   * 选中商品 sku
   * @param key 商品规格 key
   * @param attr 商品属性 值
   */
  selectGoods(key, attr) {
    const { goods } = this.props
    const { checked, specList, skuList } = this.state
    checked[key] = checked[key] == attr ? '' : attr
    const data = selectGoodsSku(checked, specList, skuList)
    this.setState({
      checked,
      specList: data.specList,
      goodsInfo: data.goodsInfo || filterGoodsInfo(goods)
    })
  }

  render() {
    const { goods = {}, isOpened, onClose, replacePrice = 'salePrice' } = this.props
    const { checked, goodsInfo, goodsNum, specList } = this.state
    const bool = isOpened ? 'enter' : 'leave'
    const check = checked.filter(Boolean)
    const disabled = !goods.isSku ? (
      //  普通商品
      goodsNum <= goods.stockNumber
    ) : (
      //  sku 商品
      (goodsNum <= goodsInfo.stockNumber) && (check.length === specList.length)
    )
    const limitNumber = goods.limitNumber ? goods.limitNumber : (goodsInfo.stockNumber || 1)
    // @ts-ignore
    return (<View catchtouchmove>
      <View className={`xf-overlay xf-fade-${bool}`} onClick={() => onClose()} />
      <View className={classNames(`xf-popup xf-popup--bottom xf-popup--round ${prefixCls}`, {
        [`xf-slide-bottom xf-slide-${bool}`]: !isOpened,
      })}>
        <View className={`${prefixCls}__goods`}>
          <Image src={goodsInfo.images} className={`${prefixCls}__goods-img`} />
          <View className={`${prefixCls}__goods-info`}>
            <View className={`${prefixCls}__goods-price d-f a-i-b`}>
              {goodsScore(goods.needScore) && <NeedScore goods={goods} priceSize={44} className='m-r-10' />}
              <SalePrice price={goodsInfo[replacePrice]} priceSize={32} />
              {Number(goodsInfo.originPrice) > 0 && <s className='originPrice'>￥{Number(goodsInfo.originPrice)}</s>}
              {/*<GoodsPrice sale={goodsInfo[replacePrice]} saleSize={36} className='m-r-10'/>*/}
              {/*{showMemberPrice(goodsInfo) && <MemberPrice price={goodsInfo.memberPrice}/>}*/}
            </View>
            <Text className={`${prefixCls}__goods-num`}>仅剩余 {goodsInfo.stockNumber} 件</Text>
            {!!check.length && <View className={`${prefixCls}__goods-attr t-o-e-2`}>
              已选：<Text className={`${prefixCls}__goods-attr-text`}>{check.join('、')}</Text>
            </View>}
          </View>
        </View>
        {!!specList.length && <View className={`${prefixCls}__spec-list`}>
          {specList.map((spec, k) => {
            return (<View key={k} className={`${prefixCls}__spec-item`}>
              <View className='title'>{spec.name}</View>
              <View className={`${prefixCls}__attr-list`}>
                {spec.list.map((attr, key) => {
                  const disabled = spec.options.indexOf(attr) == -1
                  return (<View
                    key={key}
                    className={classNames(`${prefixCls}__attr-item f-g-5`, {
                      [`${prefixCls}__attr-active`]: checked[k] === attr,
                      [`${prefixCls}__attr-disabled`]: disabled,
                    })}
                    onClick={!disabled ? this.selectGoods.bind(this, k, attr) : fun}>{attr}</View>)
                })}
              </View>
            </View>)
          })}
        </View>}
        {/* <View className={`${prefixCls}__number`}>
          <View className={`${prefixCls}__number-text`}>数量</View>
          <GoodsNumber min={1} max={limitNumber} value={goodsNum} onChange={this.changeGoodsNum.bind(this)} />
        </View> */}
        <View>
          <ReceivingAddress ref="ReceivingAddress" showBottom = {true}/>
        </View>
        {/* <View className={`${prefixCls}__number`}>
          <View className={`${prefixCls}__number-text`}>合计</View>
          <b className='totalPrice'>{formatAmount(Number(goodsInfo[replacePrice]) * Number(goodsNum))}元</b>
        </View> */}
        <Button  className={`${prefixCls}__submit-btn`} hoverClass='hover-class--btn' onClick={this.onConfirm.bind(this)}>
          {goods.isSku && check.length !== specList.length ? '请选择' : '立即兑换'}
        </Button>
      </View>
    </View>)
  }
}
